/**
 * @desc: 新增/编辑寄件地址信息面板弹框
 * @item {object} 需要用来回显的数据
 * @title {string} 标题
 * @visible { bool} 
 * @handleOK { func} 点击保存后的回调
 * @handleCancel {func} 点击取消弹框事件
 * @isSave {bool} 是否需要保存地址到用户表中
 */

import React, { useState, useEffect } from 'react';
import { Form, Input, Cascader, Button, message } from 'antd';
import CommonModal from '@/components/CommonModal';
import CommonLoading from '@/components/CommonLoading';
import { layout2 } from '@/utils/config';
import { getAllArea, addMailAddress, editMailAddress } from '@/services/common';
import { find, isEmpty } from 'lodash';
import { mobile } from '@/utils/rule';
import { customTrimFunc } from '@/utils/utils.jsx'
import styles from './index.module.less';

const { TextArea } = Input

export default ({ item = {}, title, handleOk, handleCancel, addresstype, type }) => {

    const [form] = Form.useForm();
    const [phone, setPhone] = useState(true);
    const [data, setData] = useState([]);
    const [loading, setLoading] = useState(false);
    const [receiveObj, setObj] = useState({});
    const [open, setOpen] = useState(false);
    const [isOk, setIsOk] = useState(false);

    useEffect(() => {

        getAreaList();
        const obj = {};
        obj.provinceName = item.provinceName;
        obj.cityName = item.cityName;
        obj.areaName = item.areaName;
        setObj(obj);
        setOpen(true);
    }, [])

    const getAreaList = async () => {
        const res = await getAllArea();
        if (res.success) {
            setData(res.data);
        }
    }

    const onOk = () => {
        if (loading) {
            return false;
        }
        form.validateFields().then(val => {
            handleSaveData(val);
        }).catch(err => {

        })
    }

    const handleSaveData = async val => {
        setLoading(true);
        // 调用保存接口
        const { name, mobPhone, telPhone, area, address } = val;
        const obj1 = customTrimFunc({
            name,
            mobPhone,
            telPhone,
            areaId: area[2],
            address,
            type: addresstype,
            provinceId: area[0],
            cityId: area[1],
            provinceName: receiveObj.provinceName,
            cityName: receiveObj.cityName,
            areaName: receiveObj.areaName
        })
        if (item.id) {
            Object.assign(obj1, { id: item.id, userId: item.userId })
        }
        if (type) {
            const res = await addMailAddress(obj1);
            if (res.success) {
                message.success('新增成功！');
                setIsOk(true);
                setOpen(false);
            }
            let timer = setTimeout(() => {
                setLoading(false);
                clearTimeout(timer);
                timer = null;
            }, 300)
        } else {
            const res = await editMailAddress(obj1);
            if (res.success) {
                message.success('编辑成功！');
                setIsOk(true);
                setOpen(false);
            }
            let timer = setTimeout(() => {
                setLoading(false);
                clearTimeout(timer);
                timer = null;
            }, 300)
        }
    }

    const handleChange = (_, option) => {
        if (!isEmpty(option)) {
            const obj = {};
            obj.provinceName = option[0].name;
            obj.cityName = option[1].name;
            obj.areaName = option[2].name;
            setObj(obj);
        } else {
            setObj({})
        }
    }

    const handleFormatData = () => {
        const val = form.getFieldValue('message');
        if (val) {
            try {
                const result = AddressParse.parse(val)[0];
                let provinceId, cityId, areaId;
                if (result.province && result.city && result.area) {
                    const proObj = find(data, ['name', result.province.replace('省', '')]);
                    provinceId = proObj.id;
                    const cityObj = find(proObj.childs, ['name', result.city]);
                    cityId = cityObj.id;
                    const areaObj = find(cityObj.childs, ['name', result.area])
                    areaId = areaObj.id;
                    const obj2 = {};
                    obj2.provinceName = result.province;
                    obj2.cityName = result.city;
                    obj2.areaName = result.area;
                    setObj(obj2);
                }
                form.setFieldsValue({
                    name: result.name,
                    mobPhone: result.mobile,
                    telPhone: result.phone,
                    address: result.details.length > 120 ? result.details.slice(0, 120) : result.details,
                    area: provinceId ? [provinceId, cityId, areaId] : undefined,
                })
            } catch (error) {
                message.error('地址识别失败');
            }
        } else {
            message.warning('请输入识别内容！')
        }
    }

    const onCancel = () => {
        setOpen(false);
    }

    const afterClose = () => {
        if (isOk) {
            handleOk();
        } else {
            handleCancel();
        }
    }

    return (
        <CommonModal
            title={title}
            open={open}
            onOk={onOk}
            onCancel={onCancel}
            afterClose={afterClose}
            width={600}
        >
            <Form {...layout2} form={form} className={styles.fromItem} initialValues={{ ...item }} name="address-manage-modal">
                <Form.Item name="message" label="地址识别" extra='复制第三方订单详情页的收货地址，然后点击右侧的“一键识别” 如：【李**，13658626452，广东省 广州市 天河区 *********，000022】'>
                    <div style={{ display: 'flex' }}>
                        <TextArea rows={3} />
                        <Button style={{ marginLeft: '12px' }} onClick={handleFormatData}>一键识别</Button>
                    </div>
                </Form.Item>
                <Form.Item name="name" label={addresstype !== 0 ? "寄件人" : '收件人'} rules={
                    [
                        { required: true, message: '寄件人不能为空' }
                    ]
                }>
                    <Input placeholder="最多30个字符" maxLength="30" />
                </Form.Item>
                <Form.Item shouldUpdate name="mobPhone" label="手机号"
                    rules={
                        [
                            { required: true, message: '请输入手机号' },
                            mobile
                        ]}
                >
                    <Input maxLength={11} placeholder="请填写手机号，格式：18888888888" />
                </Form.Item>
                <Form.Item name="telPhone" label="座机号"
                    rules={
                        [
                            phone
                        ]}
                >
                    <Input maxLength='15' placeholder="请填写座机号，格式：0573-88888888" />
                </Form.Item>
                <Form.Item name="area" label="所在地区" rules={
                    [
                        { required: true, message: '地区未选择' }
                    ]
                }>
                    <Cascader options={data} onChange={handleChange} fieldNames={{ label: 'name', value: 'id', children: 'childs' }} placeholder="请选择地区" />
                </Form.Item>
                <Form.Item name="address" label="详细地址" rules={
                    [
                        { required: true, message: '详细地址未填写', }
                    ]
                }>
                    <TextArea rows={4} maxLength="120" placeholder="最多120个字符" />
                </Form.Item>
            </Form>
            <CommonLoading loading={loading} />
        </CommonModal>
    )
}